from typing import List, Dict, Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Path
from sqlalchemy.ext.asyncio import AsyncSession
from app.cache.decorators import cached

from app.database import get_db
from app.schemas.schemas import (
    ResponseBase, SchoolListResponse, SchoolResponse, ClassFiltersResponse, 
    ClassListResponse, ClassCoursesResponse, ClassResponse
)
from app.crud import crud_school, crud_class, crud_course

# 创建API路由
router = APIRouter(prefix="/api/v1")

@router.get("/schools", response_model=SchoolListResponse)
@cached(ttl=3600, key_prefix="schools")
async def get_schools(db: AsyncSession = Depends(get_db)):
    """
    获取所有学校
    """
    schools_from_db = await crud_school.get_schools(db)
    # 手动将SQLAlchemy模型列表转换为Pydantic模型列表
    schools_response = [SchoolResponse.model_validate(s) for s in schools_from_db]
    return {
        "code": 200,
        "data": schools_response,
        "message": "success"
    }

@router.get("/classes/filters", response_model=ClassFiltersResponse)
@cached(ttl=3600, key_prefix="class_filters")
async def get_class_filters(
    school_id: int = Query(..., description="学校ID"),
    db: AsyncSession = Depends(get_db)
):
    """
    获取班级筛选条件
    """
    filters = await crud_class.get_class_filters(db, school_id)
    return {
        "code": 200,
        "data": filters,
        "message": "success"
    }

@router.get("/classes", response_model=ClassListResponse)
@cached(ttl=300, key_prefix="classes")
async def get_classes(
    school_id: int = Query(..., description="学校ID"),
    academic_year: Optional[str] = Query(None, description="学年名称"),
    term: Optional[str] = Query(None, description="学期代码"),
    campus: Optional[str] = Query(None, description="校区名称"),
    college: Optional[str] = Query(None, description="学院名称"),
    grade: Optional[str] = Query(None, description="年级名称"),
    major: Optional[str] = Query(None, description="专业名称"),
    education_level: Optional[str] = Query(None, description="培养层次"),
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    db: AsyncSession = Depends(get_db)
):
    """
    获取班级列表
    """
    classes, total = await crud_class.get_classes(
        db, school_id, academic_year, term, campus, college, 
        grade, major, education_level, page, size
    )
    
    # 手动将SQLAlchemy模型列表转换为Pydantic模型列表
    classes_response = [ClassResponse.model_validate(c) for c in classes]
    
    return {
        "code": 200,
        "data": {
            "list": classes_response,
            "total": total
        },
        "message": "success"
    }

@router.get("/classes/{class_code}/courses", response_model=ClassCoursesResponse)
@cached(ttl=300, key_prefix="class_courses")
async def get_class_courses(
    class_code: str = Path(..., description="班级编号"),
    week: Optional[int] = Query(None, ge=1, le=20, description="周次(1-20)"),
    day: Optional[int] = Query(None, ge=1, le=7, description="星期几(1-7)"),
    db: AsyncSession = Depends(get_db)
):
    """
    获取班级课程表
    """
    result = await crud_course.get_class_courses(db, class_code, week, day)
    
    if not result:
        raise HTTPException(status_code=404, detail="班级不存在")
    
    return {
        "code": 200,
        "data": result,
        "message": "success"
    }
